package node;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class NodeThread extends Thread{
	
	private Socket socket;
	private int port;
	public Integer executingCount = 0;
	public NodeThread(Socket socket,int port) {
		this.socket = socket;
		this.port = port;
	}

	private BufferedWriter getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new BufferedWriter(new OutputStreamWriter(socketOut));
	}

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}

	public String echo(String msg) {
		return "echo:" + msg;
	}

	public void run() {
		System.out.println("-----------------Node  start------------------");
		try {
			System.out.println("Node---socket info:"
					+ socket.getInetAddress() + ":" + socket.getPort());
			BufferedReader br = getReader(socket);
			BufferedWriter pw = getWriter(socket);
			String msg = null;
			while ((msg = br.readLine()) != null) {
				System.out.println("Node---" +  msg);
				if(msg.startsWith("execute")){
					
					new NodeExecuteThread(this,pw,port,msg).start();
//					pw.write("command already accept,please waiting executing.\r\n");
//					pw.flush();
					
//					if(executingCount <= 0){
//						new NodeExecuteThread(this,pw,port,msg).start();
//						pw.write("command already accept,please waiting executing.\r\n");
//						pw.flush();
//					}else{
//						pw.write(port+"node is busy...\r\n");
//						pw.flush();
//					}
				}
				if (msg.equals("Upgrade: websocket"))
					break;
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("-----------------Node  end------------------");
	}
	
}
